package com.stylefeng.guns.core.shiro.filter;

import com.stylefeng.guns.core.base.tips.ResultTip;
import com.stylefeng.guns.core.constant.AppCodeEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Admin on 2017/10/4.
 */
public class AJaxLoginAuthenticationFilter extends AuthorizationFilter {
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if(SecurityUtils.getSubject().getPrincipal()==null) {
            return false;
        }
        return true;//已经登录过
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))){
            resp.setCharacterEncoding("utf-8");
            String path = ((HttpServletRequest) request).getServletPath();
            if(path.contains("login")){
                return true;
            }else{
                ResultTip<String> resultTip = new ResultTip<>(AppCodeEnum.LOGIN_TIMEOUT,resp.getWriter());
            }
            return false;
        }
        return false;
    }
}
